package com.gqj.elec.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis服务
 */
@Component
public class RedisStringService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 设置string值
     *
     * @param key    key
     * @param value  value
     * @param expire 有效期（秒）
     */
    public void setRedis(String key, String value, Integer expire) {
        redisTemplate.opsForValue().set(key, value, expire, TimeUnit.SECONDS);
    }

    public void setRedis(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public String getRedis(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 判断某个key是否存在
     */
    public boolean haskey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 删除某个key
     */
    public boolean delKey(String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 设置key的过期时间
     */
    public boolean expire(String key, Integer expire) {
        return redisTemplate.expire(key, expire, TimeUnit.SECONDS);//设
    }

    /**
     * 增加(自增长), 负数则为自减
     *
     * @param key
     * @return
     */
    public Long incrBy(String key, long increment) {
        return redisTemplate.opsForValue().increment(key, increment);
    }

    /**
     * @param key
     * @return
     */
    public Double incrByFloat(String key, double increment) {
        return redisTemplate.opsForValue().increment(key, increment);
    }

    /**
     * 追加到末尾
     *
     * @param key
     * @param value
     * @return
     */
    public Integer append(String key, String value) {
        return redisTemplate.opsForValue().append(key, value);
    }

    /**
     * 获取当前键值的过期时间
     * @param key 键值
     * @return Long
     */
    public Long seconds(String key){
        return redisTemplate.opsForValue().getOperations().getExpire(key);
    }
}
